package cn.edu.lcvc.ebuy_23rj2.web.controller.backstage;


import cn.edu.lcvc.ebuy_23rj2.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class LoginLogoutController {

    @Autowired
    private AdminService adminService;

    @ResponseBody
    @RequestMapping(method=RequestMethod.POST,value="/backstage/login")
    public Map<String,Object> login(String username, String password, HttpSession session){
        Map<String,Object> map=new HashMap<>();
        if(adminService.login(username,password)){//如果密码正确
            //将登录后的用户信息保存到服务器中。
            //session对象的存储有效期：如果浏览器关闭则session对象被清空；session的默认有效期是20分钟，如果20分钟内不执行本站的任何操作则本站session自动销毁
            session.setAttribute("admin",adminService.getAdminByUsername(username));
            //如果登录成功，则跳转到后台管理系统首页(main.html)
            map.put("success",true);
        }else{//如果密码错误
            //如果登录失败，则跳转到后台管理系统登录页面(login.html)
            map.put("success",false);
            map.put("msg","登录失败：密码错误");
        }
        return map;
    }

    @RequestMapping(method=RequestMethod.GET,value="/backstage/logout")
    public String logout(HttpSession session){
        //removeAttribute相当于将值从session对象的name属性中移除
        session.removeAttribute("admin");
        //跳转到登录页面
        return "redirect:/jsp/backstage/login.jsp";
    }
}
